using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.Globalization;

using System.Resources;
using System.Reflection;

using GSNConf.Rules;
using GSN.Rules;
using GSN.Senders;
using GSN.Config;

namespace GSNConf
{
    public partial class Form1 : Form
    {
        private GSNSettings settings = new GSNSettings();
        
        public Form1()
        {
            settings.load();
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
            InitializeComponent();
        }

        private void GSNConfForm_Load(object sender, EventArgs e)
        {
            // load sms providers
            ISMSSender[] smsSenders = { new GSN.Senders.ICQSMSSender(), 
                                                new GSN.Senders.SkypeSMSSender(),
                                                new GSN.Senders.MagtifunSender(),
                                                /*@@@new GSN.Senders.ForeverSMSSender()*/ };
            cbSmsProviders.Items.Clear();
            cbSmsProviders.Items.AddRange(smsSenders);   

            settings.setSavedSettings(this);

            showControls();

            // init help
            helpProvider1.SetShowHelp(btnSmsSettings, true);
            helpProvider1.SetHelpString(btnSmsSettings, "Shows settings for chosen SMS provider.");

            helpProvider1.SetShowHelp(txtPhoneNumber, true);
            helpProvider1.SetHelpString(txtPhoneNumber, "This is the phone number where the notification SMS messages will be sent to.");

            helpProvider1.SetShowHelp(cbAutoVersionCheck, true);
            helpProvider1.SetHelpString(cbAutoVersionCheck, "If this is checked, GSN will automatically check on startup if a new version exists.");

            helpProvider1.SetShowHelp(cbPasswordsEncrypted, true);
            helpProvider1.SetHelpString(cbPasswordsEncrypted, "If this is checked, the passwords in GSN settings file will be saved as an encrypted string.");

            helpProvider1.SetShowHelp(cbSmsProviders, true);
            helpProvider1.SetHelpString(cbSmsProviders, "Select the SMS provider GSN will use to send the notification messages.");

            helpProvider1.SetShowHelp(cbLogging, true);
            helpProvider1.SetHelpString(cbLogging, "If this is checked, GSN will keep a log file with all activity made.");

            helpProvider1.SetShowHelp(txtSmsTemplate, true);
            helpProvider1.SetHelpString(txtSmsTemplate, "The template for the SMS message that will be sent to you.");

            helpProvider1.SetShowHelp(boxMailType, true);
            helpProvider1.SetHelpString(boxMailType, "Type of your e-mail account.");

            helpProvider1.SetShowHelp(listRules, true);
            helpProvider1.SetHelpString(listRules, "List of active rules. Each messae must pass all the rules in list in order to be sent. Rules are optional.");

            helpProvider1.SetShowHelp(btnAdd, true);
            helpProvider1.SetHelpString(btnAdd, "Add a new rule.");

            helpProvider1.SetShowHelp(btnChange, true);
            helpProvider1.SetHelpString(btnChange, "Change selected rule settings.");

            helpProvider1.SetShowHelp(btnRemove, true);
            helpProvider1.SetHelpString(btnRemove, "Remove selected rule.");

            helpProvider1.SetShowHelp(txtLabels, true);
            helpProvider1.SetHelpString(txtLabels, "Gmail labels to check in addition to your inbox.");

            helpProvider1.SetShowHelp(txtUsername, true);
            helpProvider1.SetHelpString(txtUsername, "E-mail account username.");

            helpProvider1.SetShowHelp(txtPassword, true);
            helpProvider1.SetHelpString(txtPassword, "E-mail account password.");

            helpProvider1.SetShowHelp(txtServer, true);
            helpProvider1.SetHelpString(txtServer, "POP3 Server address.");

            helpProvider1.SetShowHelp(txtPort, true);
            helpProvider1.SetHelpString(txtPort, "POP3 Server port. Default: 110.");

        }

        private void txtIcqUin_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)))
            {
                e.Handled = true;                
            }
        }

        private void txtPhoneNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == '+' || e.KeyChar == '-' || e.KeyChar == 8))
            {
                e.Handled = true;
            }

        }

        private void txtPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar))
                e.Handled = true;
        }

        private void boxMailType_SelectionChangeCommitted(object sender, EventArgs e)
        {
            showControls();
        }

        /// <summary>
        /// shows "mail type" settings controls
        /// </summary>
        private void showControls()
        {
            if (boxMailType.SelectedItem != null)
            {
                txtServer.Visible = txtPort.Visible = lblServer.Visible = lblPort.Visible = (boxMailType.SelectedItem.ToString().ToUpper() == "POP3" || boxMailType.SelectedItem.ToString().ToUpper() == "IMAP");
                lblLabels2.Visible = txtLabels.Visible = lblLabels.Visible = (boxMailType.SelectedItem.ToString().ToUpper() == "GMAIL");
                switch (boxMailType.SelectedItem.ToString().ToUpper())
                {
                    case "POP3":
                        txtPort.Text = "110";
                        break;
                    case "IMAP":
                        txtPort.Text = "143";
                        break;
                }
            }
        }

        private void saveSettings()
        {
            settings.getFormSettings(this);
            settings.save();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                saveSettings();
            }
            catch (SettingsException se)
            {
                errorBox(se.Message);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void errorBox(string str)
        {
            MessageBox.Show(str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                DialogResult res = MessageBox.Show(
                    "Save Settings Before Exit?", "Save", 
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                switch (res)
                {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                    case DialogResult.Yes:
                        saveSettings();
                        break;
                }
            }
            catch (SettingsException se)
            {
                e.Cancel = true;
                errorBox(se.Message);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddRuleForm f = new AddRuleForm();
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                if (f.selectedRule.showConfigDialog((IConfigurator)Activator.CreateInstance(Type.GetType(f.selectedRule.getConfiguratorTypeName()))))
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = f.selectedRule.getName();
                    item.SubItems.Add(f.selectedRule.getDescription());
                    item.Tag = f.selectedRule;
                    listRules.Items.Add(item);
                }
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (listRules.SelectedItems.Count > 0)
                listRules.SelectedItems[0].Remove();
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            if (listRules.SelectedItems.Count <= 0)
                return;

            IRule rule = (IRule)listRules.SelectedItems[0].Tag;

            if (rule.showConfigDialog((IConfigurator)Activator.CreateInstance(Type.GetType(rule.getConfiguratorTypeName()))))
            {
                listRules.SelectedItems[0].Tag = rule; // neccessary?
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            MessageBoxOptions mbOptions = 0;

            if (Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft)            
            {
                mbOptions = MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading;
            }

            MessageBox.Show(this, GSNConf.Properties.Resources.SMS_TEMPLATE_HELP.Replace("\\n", Environment.NewLine),
                "SMS Template Help", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, 
                mbOptions);
            

        }

        private void needHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show(this, "Need Help? E-mail support at ran.manor@hotmail.com .", "GSN Help",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnSmsSettings_Click(object sender, EventArgs e)
        {
            if (cbSmsProviders.SelectedIndex >= 0)
            {
                IConfigurable c = (IConfigurable)cbSmsProviders.SelectedItem;
                c.showConfigDialog((IConfigurator)Activator.CreateInstance(Type.GetType(c.getConfiguratorTypeName())));

                //((IConfigurable)cbSmsProviders.SelectedItem).showConfigDialog(
            }
        }

        private void cbLanguages_SelectedIndexChanged(object sender, EventArgs e)
        {
            // @@@ add note that this requires restart
            /*switch (cbLanguages.SelectedIndex)
            {
                case 0:
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
                    break;
                case 1:
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("he");
                    break;
            }*/
        }
  
    }
}